from fastapi import FastAPI
from fastapi_amis_admin.admin.settings import Settings
from fastapi_user_auth.admin.site import AuthAdminSite
from starlette.requests import Request
from sqlmodel import SQLModel

# Create FastAPI application
app = FastAPI()

# Create AdminSite instance
site = AuthAdminSite(settings=Settings(database_url='sqlite:///amisadmin.db?check_same_thread=False'))
auth = site.auth
# Mount the backend management system
site.mount_app(app)


# Create initial database table
@app.on_event("startup")
async def startup():
    await site.db.async_run_sync(SQLModel.metadata.create_all, is_session=False)
    # Create a default administrator, username: admin, password: admin, please change the password in time!!!
    await auth.create_role_user("admin")
    #Create the default super administrator, username: root, password: root, please change the password in time!!!    await auth.create_role_user("root")
    # Run the startup method of the site, load the casbin strategy, etc.
    await site.router.startup()
    #Add a default casbin rule
    if not auth.enforcer.enforce("u:admin", site.unique_id, "page", "page"):
        await auth.enforcer.add_policy("u:admin", site.unique_id, "page", "page", "allow")


# Requirements: User must be logged in
@app.get("/auth/get_user")
@auth.requires()
def get_user(request: Request):
    return request.user


if __name__ == '__main__':
    import uvicorn

    uvicorn.run(app,port=18000)
